<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/12
 * Time: 17:17
 */

namespace Modules\Api\Service;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\UsersIntegralRepository;
use HiCommon\Repository\UsersJpushSetRepository;
use HiCommon\Repository\UsersLevelRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\OrderCheckpointRepository;
use HiCommon\Repository\EquitiesRepository;
use HiCommon\Repository\ShopUserRepository;
use HiCommon\Service\LoginUserService;

class UserService extends BaseService
{

    /**
     *  获取用户的积分明细
     *  hinq 2019 11 12
     *
     **/
    public function integral_detail( array $arr_input ){
        try{
            $user_id = api_user_id();
            $arr_option['where'] = ['user_id'=>$user_id];
            $arr_option['order'] = ['key'=>'created_at','value'=>'desc'];
            $arr_option['field'] = ['id','user_id','type','deduct','surplus','order_id','order_type','remarks','created_at'];
            //获取指定条件的数据
            $arr_list = UsersIntegralRepository::get_list( (array) $arr_input , (array) $arr_option )->toArray();
            $arr_add = 0;  //增加的总积分
            foreach ( $arr_list['data'] as $key => $vo ){
                if( $vo['type'] == 1 ){  //获取用户增加的积分统计数据  type:1 添加积分  2：扣除积分
                    $arr_add += $vo['deduct'];
                }
            }
            //获取当前用户的账户信息
            $user_option['field'] = ['id','integral','integral_all'];
            $user_info = UsersRepository::get_one( (int) $user_id ,(array) $user_option );
            $data = list_page_data_for_api( $arr_list );
            $data['user']['add'] = $arr_add;   //指定条件增加的积分
            $data['user']['all'] = $user_info['integral'];        //用户的所有积分
            return hello_success('ok',$data);
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *	获取所有的vip等级
     *	hinq 2019 09 02
     *	使用场景【个人中心 VIP会员】
     **/
    public function get_vip_list(){
        //获取所有vip会员等级
        $temp_where['field'] = ['id','name','min_integral','max_integral','equities'];
        $temp_where['order'] =[ 'key'=>'min_integral','value'=>'asc'];  //按积分大小排序
        $arr_vip_list = UsersLevelRepository::get_all( (array) $temp_where )->toarray();

        //获取当前用户的信息
        $arr_where['field'] = ['id','nickname','head_img','integral','integral_all'];
        $user_id = api_user_id();
        $arr_user_info = UsersRepository::get_one( (int) $user_id ,(array) $arr_where );
        if( empty( $arr_user_info->first() ) ){
            return hello_error('用户信息错误');
        }

        //验证当前用户所
        foreach ($arr_vip_list as $key => $value) {
            $arr_vip_list[$key]['checked'] = false;
            // 当前登录用户的累计积分总数        >=      会员等级设置的最小数       当前登录用户的累计积分总数 <= 会员等级最大数
            if( intval( $arr_user_info['integral_all']) >= $value['min_integral'] && intval( $arr_user_info['integral_all']) <= $value['max_integral'] ){
                $arr_vip_list[$key]['checked'] = true;
                $arr_user_info['level_name'] = $value['name'];
                $arr_user_info['level_max_integral'] = $value['max_integral'];
                $arr_user_info['level_id'] = $value['id'];
                $arr_user_info['level_equities_num'] = count( explode(',', $value['equities']) );
            }
            $arr_vip_list[$key]['equities'] = explode(',', $value['equities']);   //当前会员的
        }
        //获取所有的权益数据
        $arr_where['field'] =[ 'id','name','img','remark'];
        $arr_where['order'] =[ 'key'=>'id','value'=>'asc'];
        $arr_equities = EquitiesRepository::get_all( (array) $arr_where );
        foreach ($arr_vip_list as $k => $val) {
            if( $val['checked'] ){
                //遍历权益列表，判断当前用户是否有这种权益
                foreach ($arr_equities as $key => &$value) {
                    $value['img'] = oss_full_url( $value['img']);
                    if( in_array($value['id'], $val['equities']) ){
                        $value['selected'] = true;
                    }else{
                        $value['selected'] = false;
                    }
                }
            }
        }
        $arr_list['vipList'] = $arr_vip_list;
        $arr_list['userInfo'] = $arr_user_info;
        $arr_list['equities'] = $arr_equities;
        return hello_success( 'ok' , $arr_list );
    }


    /**
     *  修改手机号码
     *  hinq 2019 11 13
     *
     **/
    public function update_one( array $arrInput ){
        try {
            //如果有手机号码  验证手机号码格式
            if( !empty( $arrInput['phone'] ) ){
                if( !preg_match("/^1[34578]{1}\d{9}$/",$arrInput['phone'])){
                    return ['state'=> 1,'msg'=>'手机号码格式不正确','data'=>[],'error'=>''];
                }

                if( empty( $arrInput['code'] ) ){
                    return ['state'=> 1,'msg'=>'请填写短信验证码','data'=>[],'error'=>''];
                }
                //验证手机号码+验证码是否输入成功   有用不可删除
                $check = check_phone_code( $arrInput['phone'] , $arrInput['code'] );
                if( $check['state'] != 0){
                    return $check;
                }
                unset( $arrInput['code'] );
            }
            $user_id = api_user_id();
            $arrInput['id'] = $user_id;

            $result = LoginUserService::api_edit_user($arrInput);
            if($result['state'] != 0){
                return $result;
            }

            return hello_success('修改成功');
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  修改指定用户的基本信息
     *  hinq 2019 12 09
     *
     **/
    public function update_info( array $arr_input ,$user){
        try{
            if( !empty( $arr_input['head_img'] ) ){     //用户的头像
                $data['head_img'] = $arr_input['head_img'];
            }
            if( !empty( $arr_input['nickname'] ) ){
                //用户的昵称
                $arr_input['nickname'] = str_trim($arr_input['nickname']);
                if(mb_strlen($arr_input['nickname']) > 11 ){
                    return hello_error('昵称不能超过11个字符');
                }
                $data['nickname'] = $arr_input['nickname'];
            }
            if( !empty( $arr_input['sex']) ){
                //用户的性别
                $arr_input['sex'] = intval($arr_input['sex']);
                if(!in_array($arr_input['sex'],[1,2,3])){
                    return hello_error('性别参数错误');
                }
                $data['sex'] = $arr_input['sex'];
            }
            if( !empty( $arr_input['birthday'] ) ){     //生日信息
                $data['birthday'] = $arr_input['birthday'];
            }
            if( empty( $data ) ){
                return hello_error('参数错误');
            }
            //如果更改了头像或者用户昵称   要同步修改融云上绑定的用户信息
            if( !empty( $arr_input['head_img'] )  || !empty( $arr_input['nickname'] ) ){
                $temp['userId'] = $user['username'];   //用户的唯一标示
                $temp['name'] = empty( $arr_input['nickname'] ) ? $user['nickname'] : $arr_input['nickname'];  //用户昵称
                $temp['portraitUri'] = empty( $arr_input['head_img'] ) ? oss_full_url($user['head_img']) : $arr_input['head_img'];   //用户头像
                \HiCommon\Service\RongService::userRefresh( (array) $temp );  //更新用户在融云上绑定的信息
            }
            $data['id'] = $user['id'];
            $res = UsersRepository::edit_one( (array) $data );
            if( empty( $res ) ){
                return hello_error('修改失败');
            }
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    public function get_user_viplist(){
        try{
            //获取当前用户的基本信息
            $user_id = api_user_id();
            $arr_option['field'] = ['id','head_img','nickname','integral','integral_all'];
            $user_info = UsersRepository::get_one( (int) $user_id , (array) $arr_option )->toArray();
            //获取权益列表
            $exception_option['field'] = ['id','name','remark','img','is_gifts'];
            $equitie_list = EquitiesRepository::get_all( (array) $exception_option )->toArray();
            //获取所有的会员等级列表
            $level_option['field'] = ['id','name','min_integral','max_integral','equities'];
            $users_level_list = UsersLevelRepository::get_all( (array) $level_option )->toArray();
            $user_equities = [];
            //判断当前用户的会员等级
            foreach ( $users_level_list as $key => &$vo ){
                $vo['equities'] = explode(',' , $vo['equities']);
                if( $user_info['integral_all'] >= $vo['min_integral'] && $user_info['integral_all'] <= $vo['max_integral'] ){
                    $vo['jindu'] = $vo['max_integral'] - $user_info['integral_all'];
                    $user_info['level_info'] = $vo;
                }
            }
            //判断当前用户所拥有的权益
            foreach ( $equitie_list as $key => &$vo ){
                $vo['is_check'] = false;
                if( in_array( $vo['id'] , $user_equities ) ){
                    $vo['is_check'] = true;
                }
            }
            $data['user'] = $user_info;
            $data['level_list'] = $users_level_list;
            $data['equitie_list'] = $equitie_list;
            return hello_success('ok',$data);
       }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取当前用户的详细信息
     *  hinq 2019 12 25
     *
     **/
    public function user_detail(){
        try{
            //获取当前用户的信息
            $user_id = api_user_id();
            $arr_option['field'] = ['head_img','id','wx_nickname','nickname','realname','phone','unionid','small_openid','app_openid','integral','integral_all'];
            $user_info = UsersRepository::get_one( (int) $user_id , (array) $arr_option );
            if( empty( $user_info->first() ) ){
                return hello_error('参数错误');
            }
            $user_info = $user_info->toarray();

            $user_info['headimg'] = $user_info['head_img']['full_src'];
            unset( $user_info['head_img'] );
            //获取当前用户的会员等级
            $level_info = UsersLevelRepository::get_all()->toarray();
            $user_level_name = '';
            $level_id = '';
            foreach ( $level_info as $key=>$value ){
                if( $value['min_integral'] <= $user_info['integral_all'] && $value['max_integral'] >= $user_info['integral_all'] ){
                    $user_level_name = $value['name'];
                    $level_id = $value['id'];
                }
            }
            $user_info['level_name'] = $user_level_name;
            $user_info['level_id'] = $level_id;
            //获取当前用户的优惠券统计数据
            $coupon_where = [ 'user_id' => $user_id , 'status' => 1 ];
            $user_info['coupon_count'] = CouponGrantDetailRepository::get_count_by_where( (array) $coupon_where );
            //获取当前用户的收藏的统计数据
            $collect_where = [ 'user_id' => $user_id ];
            $user_info['collect_count'] = CollectRepository::get_count_by_where( (array) $collect_where );
            //获取当前用户的预约订单统计的数据
            $checkpoint_where = [ 'user_id' => $user_id ];
            $user_info['checkpoint_count'] = OrderCheckpointRepository::get_appointing_count_by_where( (array) $checkpoint_where );
            //获取当前用户的购物车订单统计的数据
            $user_info['shopping_count'] = \Modules\Api\Service\StoreCarService::get_car_goods_total();
            //获取当前用户的系统消息统计的数据
            $user_info['message_count'] = 0;    //前端自己统计 有单独的统计接口
            //获取当前用户的普通订单统计的数据
            $user_info['store_order_count'] = \HiCommon\Repository\StoreOrderRepository::get_count_by_whereIn( ['pay_status'=>2 , 'user_id'=>$user_id , 'order_type'=>1] );
            //获取当前用户的积分订单的数据
            $user_info['mall_order_count'] = \HiCommon\Repository\OrderMallRepository::get_count_by_whereIn( ['pay_status'=>2 , 'user_id'=>$user_id ]);
            //获取当前用户的服务订单统计的数据
            $user_info['repairstore_order_count'] = \HiCommon\Repository\OrderRepairstoreRepository::count_by_where( ['pay_status'=>1 , 'user_id'=>$user_id , 'order_type'=>1]);
            //获取当前用户的退货、售后统计的数据
            $user_info['sales_return_count'] = 0;
            //道路救援订单统计
            $user_info['road_order_count'] = \HiCommon\Repository\RoadRescueOrderRepository::get_count_by_whereIn(['pay_status'=>1 , 'user_id'=>$user_id ]);

            /*用户绑定信息*/
            $user_info['is_bind_phone'] = 2;
//            $user_info['is_bind_wx_mini'] = 2;
            $user_info['is_bind_wx_app'] = 2;
            if(!empty($user_info['phone'])){
                $user_info['is_bind_phone'] = 1;
            }
//            if(!empty($user_info['small_openid'])){
//                $user_info['is_bind_wx_mini'] = 1;
//            }
            if(!empty($user_info['unionid'])){
                $user_info['is_bind_wx_app'] = 1;
            }

            return hello_success('ok', $user_info );
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取指定用户的基本信息
     *  hinq 2020 4 20
     *  不过是大梦一场空  不过是孤影照惊鸿 不过是白驹之过一场梦  梦里我们有相逢
     *  有道是万物皆虚空  有道是苦海
     **/
    public function get_user_info( string $shop_id ){
        try{

            if( empty( $shop_id ) ){
                return hello_error('参数错误');
            }
            //$shop_id参数融云id  有可能是商铺的  也有可能是平台的
            $temp = explode( '_', $shop_id);
            if( $temp[0] == 'shop'){   //获取商铺的信息
                $arr_field = ['id','username','avatar','phone', 'shop_id'];
                $where = ['rong_cloud_id' => $shop_id ];
                $arr_info = ShopUserRepository::get_where_one( (array) $where , (array) $arr_field );

                if( empty( $arr_info ) ){  //判断是否获取到数据 没有获取数据或报错而不是返回state = 1
                    return hello_error('参数错误',null);
                }
                if( empty( $arr_info['avatar']['full_src'] ) ){   //如果当前账户的头像为空
                    //获取当前账户的主体信息
                    $arr_option['field'] = ['id','logo'];
                    $arr_list = ShopRepository::get_one_by_where( (array) ['id'=>$arr_info['shop_id']] , (array) $arr_option );


                    $image = $arr_list['logo']['full_src'];
                }else{
                    $image = $arr_info['avatar']['full_src'];
                }
                unset( $arr_info['avatar'] );
                $arr_info['image'] = oss_full_url( $image );
            }else{  //获取平台
                $where = ['rong_cloud_id' => $shop_id];
                $arr_option['field'] = ['id','username','phone'];
                $arr_info = \HiCommon\Repository\AdminsRepository::get_one_by_where( (array) $where , (array) $arr_option  );
                if( empty( $arr_info->first() ) ){  //判断是否获取到数据 没有获取数据或报错而不是返回state = 1
                    return hello_error('参数错误' , null);
                }
                $arr_info['shop_id'] = 1;
                $arr_info['image'] = 'http://wuhaha.oss-cn-beijing.aliyuncs.com/xinda/wx/2020-05/13/200513040418_5ebbaa02a4e1e.png';
            }

            return hello_success( 'ok' , $arr_info );
        }catch (\Exception $exception ){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  通过id获取用户的get_rong_cloud_id
     *  hinq 2020 4 22
     **/
    public function get_rong_cloud_id( array $arr_input ){
        try{
            if( empty( $arr_input['shop_id'] ) ){
                return hello_error('参数错误');
            }
            if( $arr_input['shop_id'] == 1 ){   //获取平台的融云id
                $arr_option['field']= ['id','rong_cloud_id','username'];
                $where = ['shop_id' => $arr_input['shop_id'] ];
                $arr_temp = \HiCommon\Repository\AdminsRepository::get_one( $arr_input['shop_id'] , $arr_option );
                if(  empty( $arr_temp->first() ) ){
                    return hello_success('ok', []);
                }
                $arr_temp = $arr_temp->toarray();

                $arr_info = [
                    'id' => $arr_temp['id'],
                    'rong_cloud_id' => $arr_temp['rong_cloud_id'],
                    'shop_id' => 1,   //默认
                    'name' => $arr_temp['username'],
                    'image' => 'http://wuhaha.oss-cn-beijing.aliyuncs.com/xinda/wx/2020-05/13/200513040418_5ebbaa02a4e1e.png'
                ];
            }else{     //获取普通商户的融云id
                $arr_field = ['id','rong_cloud_id','shop_id'];
                $where = ['shop_id' => $arr_input['shop_id'] ];
                $arr_info = ShopUserRepository::get_where_one_with( (array) $where , (array) $arr_field , ['shop_base' => function( $query ){
                    $query->select('name','logo','id');
                }]);
                if(  empty( $arr_info ) ){
                    return hello_success('ok', []);
                }
                $arr_info['name'] = $arr_info['shop_base']['name'];
                $arr_info['image'] = oss_full_url( $arr_info['shop_base']['logo']['full_src'] );
                unset( $arr_info['shop_base'] );
            }
            return hello_success('ok', $arr_info);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }

    /**
     *  同步用户分配的极光id  方便推送使用
     *  hinq 2020 5 13
     *
     **/
    public function sync_jpush_reg_id( array $arr_input ){
        try{
            //141fe1da9e2a56e5771_ios
            $data['id'] = api_user_id();
            $data['jpush_reg_id'] =  $arr_input['reg_id'] == 'login_out' ? null : $arr_input['reg_id'];
            $res = UsersRepository::edit_one( (array) $data );
            if( empty( $res ) ){
                return hello_error('修改失败');
            }
            if( $arr_input['reg_id'] == 'login_out' ){   //退出登录
                api_offset_user();
            }
            return hello_success('ok' ,'' );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }



    /**
     *  设置是否接收推送消息
     *  hinq 2020 5 19
     *
     **/
    public function user_jpush_set( array $arr_input ){
        try{
            $user_id = api_user_id();
            $arr_input['user_id'] = $user_id;
            //查询当前用户是否有数据记录
            $count = UsersJpushSetRepository::get_count_by_where( (array) ['user_id' => $user_id] );
            if( $count == 0 ){  //添加一条记录
                $res = UsersJpushSetRepository::add_one( $arr_input );
                if( empty( $res ) ){
                    return hello_error('设置失败');
                }
                return hello_success('ok');
            }else{
                $res = UsersJpushSetRepository::edit_one_by_where( (array) ['user_id' => $user_id] ,(array) $arr_input );
                if( empty( $res ) ){
                    return hello_error('设置失败');
                }
                return hello_success('ok');
            }
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }

    /**
     *   获取用户设置是否接收推送消息
     *   hinq 2020 5 19   
     *
     **/
    public function get_jpush_set(){


        $user_id = api_user_id();
        $arr_input['field'] = ['id','user_id','sys','order','activity'];
        //查询当前用户是否有数据记录
        $arr_list = UsersJpushSetRepository::get_one_where( (array) ['user_id' => $user_id] , (array) $arr_input);
        if( empty( $arr_list->first() ) ){
            $data = [   //如果用户为设置信息 返回默认值
                'user_id' => $user_id,
                'sys' => 1,
                'order' => 1,
                'activity' => 1,
            ];
            return hello_success('ok',$data);
        }
        return hello_success('ok',$arr_list);
    }


}